package com.ruoyi.quartz.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.order.OrderUtils;
import com.ruoyi.statistic.domain.TMonthSalaryBillInfo;
import com.ruoyi.statistic.service.ITMonthSalaryBillInfoService;
import com.ruoyi.statistic.service.ITMonthSalaryWaybillRelService;
import com.ruoyi.waybill.domain.TWayBillInfo;
import com.ruoyi.waybill.service.ITWayBillInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务，工资账单，任务
 *
 * @author wzy
 */
@Component("sbTask")
public class SbTask
{
    @Autowired
    private ITWayBillInfoService tWayBillInfoService;

    @Autowired
    private ITMonthSalaryBillInfoService tMonthSalaryBillInfoService;

    @Autowired
    private ITMonthSalaryWaybillRelService tMonthSalaryWaybillRelService;

    private static Logger logger = LoggerFactory.getLogger(SbTask.class);

    /**
     * 统计月工资单，有参
     */

    public void statisticMonthSalaryBill(String strSalaryBillDate)
    {
        logger.debug("统计，月工资单，月账单，按结算客户，开始 ...");
        /**
         * 计算当前日期，前一月日期
         */
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate currentDate = LocalDate.now();
        if(StringUtils.isNotEmpty(strSalaryBillDate)) {
            currentDate = LocalDate.parse(strSalaryBillDate, formatter);
        }
        logger.debug("当前日期: " + currentDate);

        LocalDate lastMonthDate = currentDate.minusMonths(1);
        logger.debug("上月日期: " + lastMonthDate);
        LocalDate lastMonthFirstDay = lastMonthDate.with(TemporalAdjusters.firstDayOfMonth());
        logger.debug("上个月第一天：" + lastMonthFirstDay);
        LocalDate lastMonthLastDay = lastMonthDate.with(TemporalAdjusters.lastDayOfMonth());
        logger.debug("上个月最后一天：" + lastMonthLastDay);
        Date beginDate = DateUtils.toDate(lastMonthFirstDay);
        Date endDate = DateUtils.toDate(lastMonthLastDay);

        Integer monthTripNumber = 0;
        Double monthFreightWeight = 0.0;
        Double monthFreightAmount = 0.0; //主货工资(元)
        Double monthMinorFreightAmount = 0.0; //配货工资(元)
        Double monthFreightTotalAmount = 0.0; //工资总额(元)

        // 月工资 = 主货工资 + 配货工资, 工资总额，合计
        Double monthSalaryAmount = 0.0;

        String vehicleLicenseNumbers  = "";
        TMonthSalaryBillInfo tMonthSalaryBillInfo = new TMonthSalaryBillInfo();
        String monthSalaryBillNumber;
        Long monthSalaryBillId = 0L;
        List<Long> wayBillIds = new ArrayList<>();
        /**
         * 按录单日期，筛选司机姓名
         */
        List<String> driverNames = tWayBillInfoService.selectSalaryStatisticFieldByRecordDate("自有车辆", beginDate, endDate);
        logger.debug("司机姓名列表：driverNames = " + driverNames);

        /**
         * 遍历司机姓名，运单
         */
        for(String driverName : driverNames)
        {
            /**
             * 按车牌号。录单日期，查询运单
             */
            //tWayBillExt.setFreightSettlementCustomer(vehicleLicenseNumber);
            logger.debug("司机姓名：driverName = " + driverName);
            List<TWayBillInfo> wayBillInfos = tWayBillInfoService.selectTWayBillInfoUsedBySalaryStatistic(driverName, beginDate, endDate);
            //logger.debug("运单列表：wayBillInfos = " + wayBillInfos);
            /**
             * 合计工资，记录运单ID
             */
            for(TWayBillInfo wayBillInfo : wayBillInfos) {
                monthTripNumber = monthTripNumber + 1;
                monthFreightWeight = monthFreightWeight + wayBillInfo.getFreightWeight() + wayBillInfo.getMinorFreightWeight();
                monthFreightAmount = monthFreightAmount + wayBillInfo.getFreightAmount();
                monthMinorFreightAmount = monthMinorFreightAmount + wayBillInfo.getMinorFreightAmount();
                monthFreightTotalAmount = monthFreightTotalAmount + wayBillInfo.getFreightTotalAmount();

                if(!(vehicleLicenseNumbers.contains(wayBillInfo.getVehicleLicenseNumber()))) {
                    vehicleLicenseNumbers = vehicleLicenseNumbers + "," + wayBillInfo.getVehicleLicenseNumber();
                }
                wayBillIds.add(wayBillInfo.getWayBillId());
            }
            //monthSalaryAmount = monthFreightTotalAmount;
            /**
             * 月工资单编号
             */
            monthSalaryBillNumber = OrderUtils.getOrderNumber("MS", "-");
            /**
             * 工资总额，四舍五入，保留2位小数
             */
            monthFreightWeight = Math.round(monthFreightWeight * 1000.0) / 1000.0;
            monthFreightAmount = Math.round(monthFreightAmount * 100.0) / 100.0; //主货工资(元)
            monthMinorFreightAmount = Math.round(monthMinorFreightAmount * 100.0) / 100.0; //配货工资(元)
            monthFreightTotalAmount = Math.round(monthFreightTotalAmount * 100.0) / 100.0; //工资总额(元)
            /**
             * 月工资单，数据准备
             */
            tMonthSalaryBillInfo.setSalaryBillNumber(monthSalaryBillNumber);
            tMonthSalaryBillInfo.setSalaryBillMonth(DateUtils.toDate(lastMonthDate));
            tMonthSalaryBillInfo.setDriverName(driverName);
            tMonthSalaryBillInfo.setVehicleLicenseNumber(vehicleLicenseNumbers.substring(1));
            tMonthSalaryBillInfo.setVehicleMark("自有车辆");
            // 按趟计算，除以2
            monthTripNumber = monthTripNumber/2;
            tMonthSalaryBillInfo.setTripNumber(monthTripNumber);
            tMonthSalaryBillInfo.setFreightWeight(monthFreightWeight);
            tMonthSalaryBillInfo.setBasicSalary(0.0); //基本工资
            tMonthSalaryBillInfo.setUnsettledSalary(monthFreightTotalAmount); //未结工资
            tMonthSalaryBillInfo.setDeductSalary(0.0); //扣款
            tMonthSalaryBillInfo.setNetSalary(monthFreightTotalAmount); //实发工资

            tMonthSalaryBillInfo.setCreateBy("PbTask");
            tMonthSalaryBillInfo.setCreateTime(DateUtils.getNowDate());

            /**
             * 月工资单，插入数据
             */
            tMonthSalaryBillInfoService.insertTMonthSalaryBillInfo(tMonthSalaryBillInfo);
            /**
             * 获取插入记录，ID
             */
            monthSalaryBillId = tMonthSalaryBillInfo.getSalaryBillId();
            logger.debug("OOO " + "monthSalaryBillId = " + monthSalaryBillId);

            /**
             * monthFreightAmount清零
             */
            monthTripNumber = 0;
            monthFreightWeight = 0.0;
            monthFreightAmount = 0.0;
            monthMinorFreightAmount = 0.0;
            monthFreightTotalAmount = 0.0;

            /**
             * 工资运单关联表，数据插入
             */
            logger.debug("OOO " + "wayBillIds = " + wayBillIds);
            tMonthSalaryWaybillRelService.insertTMonthSalaryWayBillRelExt(monthSalaryBillId, wayBillIds);
            wayBillIds.clear();
        }
    }

}
